package validate

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/consts"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"gitee.com/bobo-rs/idea-space-framework/framework/service"
	"gitee.com/bobo-rs/idea-space-framework/pkg/utils"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gvalid"
	"regexp"
)

// RuleRegisterLabel 自定义注册-标签库
func RuleRegisterLabel() {
	gvalid.RegisterRuleByMap(map[string]gvalid.RuleFunc{
		`label-match-name`:        RuleLabelMatchName,
		`label-unique-name`:       RuleLabelUniqueName,
		`label-value-match`:       RuleLabelValueMatch,
		`label-exists`:            RuleLabelExists,
		`label-value-hash-match`:  RuleLabelValueHashMatch,
		`label-value-hash-exists`: RuleLabelValueHashExists,
		`label-value-exists`:      RuleLabelValueExists,
	})
}

// RuleLabelMatchName 自定义规则-标签名匹配规则
func RuleLabelMatchName(ctx context.Context, in gvalid.RuleFuncInput) error {

	// 验证数据
	re := regexp.MustCompile(consts.ChsAlphaNum)
	if !re.MatchString(in.Value.String()) {
		return gerror.New(`标签名只能是汉字、英文、数字以及破折号-和下划线_`)
	}
	return nil
}

// RuleLabelUniqueName 自定义规则-标签名是否存在
func RuleLabelUniqueName(ctx context.Context, in gvalid.RuleFuncInput) error {
	var (
		req = model.LabelSaveInput{}
		res bool
		err error
	)
	if err = in.Data.Struct(&req); err != nil {
		return gerror.Wrap(err, `将数据扫描到LabelSaveReq失败-unique`)
	}
	// 查询条件
	where := g.Map{`name`: req.Name}
	switch req.Id {
	case 0:
		// 添加
		res, err = service.Label().CheckLabelExists(ctx, where)
	default:
		// 编辑
		detail := model.LabelGetDetailItem{}
		err = service.Label().GetLabelDetail(ctx, where, &detail)
		if err != nil && utils.ScanIsEmpty(err.Error()) {
			// 数据为空
			err = nil
		}
		res = detail.Id > 0 && detail.Id != req.Id // 编辑时查询到标签ID大于0且不等于当前标签Id则标签存在TRUE，否则不存在且是痛标签FALSE
	}
	// 验证规则
	if err != nil {
		return gerror.Wrap(err, `检测标签失败：`+err.Error())
	}
	// 是否存在
	if res == true {
		return gerror.New(`标签类名已经存在`)
	}
	return nil
}
